<?php

class AdminClass_Controller extends Admin_Controller {
	public function index(Request $request, Response $response) {
		$size = intval($request->size) ?: 30;
		$p = intval($request->p ?: 1);
		$from = ($p - 1) * $size;
		$q = new TrueQuery();
		if ($request->search) $q = new SearchQuery('name', $request->search);
		$data = StudentClass::find($q, ['from' => $from, 'size' => $size, 'sort' => ['created' => 'ASC']]);
		$page_nav['count'] = StudentClass::totalCount($q);
		$nav = new SubPages($size, $page_nav['count'], $p, 10, "/admin/class/?p=", 2);
		$page_nav['nav'] = $nav->subPageCss2();
		$response->append(new View('admin/class/list', compact('data', 'page_nav')));
	}

	public function edit(Request $request, Response $response) {
		if (!$request->isPost()) {
			$id = $request->path(3);
			$data = StudentClass::load($id);
			if (!$id || !$data) $data = new College();
			$response->send(new View('admin/class/edit', compact('data')));
		}
		/**
		 * @var    StudentClass $data
		 */
		$data = StudentClass::createByRequest($request);
		$nullCheck = [
				'name' => '班级名称',
				'grade' => '年级',
				'collegeId' => '所属学院',
		];
		foreach ($nullCheck as $item => $description) if (!$data->$item) $response->alertErrorAndGoBack("{$description}不能为空！");
		$data->save();
		$response->alertAndGoTo('操作成功!', '/admin/class/');
	}

	public function delete(Request $request, Response $response) {
		if (!$request->path(3)) $response->alertErrorAndGoBack('请求无效！');
		/**
		 * @var StudentClass $class
		 */
		if (!($class = StudentClass::load($request->path(3)))) $response->alertAndGoTo('该记录不存在！', '/admin/class/');
		$class->remove();
		$response->alertAndGoTo('删除成功!所有相关记录已删除!', '/admin/class/');
	}
}